package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.BaseEnum.StateEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.dict.bean.DictBean;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.joint.base.entity.Company;
import com.joint.base.service.AuthCodeService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.Client;
import com.joint.core.entity.Linkman;
import com.joint.core.entity.ProInfo;
import com.joint.core.service.ClientService;
import com.joint.core.service.LinkmanService;
import com.joint.core.service.ProInfoService;
import com.joint.web.action.BaseAdminAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * Created by dqf on 2015/3/2.
 */
@ParentPackage("com")
public class AjaxClientAction extends BaseAdminAction {
    @Resource
    private ClientService clientService;
    @Resource
    private LinkmanService linkmanService;
    @Resource
    private DictService dictService;
    @Resource
    private AuthCodeService authCodeService;
    @Resource
    private ProInfoService proInfoService;

    protected Pager pager;
    protected Client client;
    protected List<Client> clientList;
    protected ArrayList<Map<String,Object>> typesArrayList;

    private String linkmanId;
    private String section;
    private String name;
    private String dictId;
    private String keyId;
    private String  subName;
    private String invoiceTitle;
    private Dict type;
    private String province;
    private String city;
    private String county;
    private String remark;
    private String situtation;
    private Set<Linkman> linkman;
    private String clientPhotoIds;

    public String list(){
        pager = new Pager();
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        if(StringUtils.isNotEmpty(sidx)&&BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("name", name);
        params = getSearchFilterParams(_search,params,filters);
        Company com = usersService.getCompanyByUser();

        pager = clientService.findByPagerAndCompany(pager, null, com, params);

        clientList = (List<Client>) pager.getList();
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Client client:clientList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",client.getId());
            rMap.put("name",client.getName());
            rMap.put("subname",client.getSubName());
            rMap.put("type",client.getType()!=null ? client.getType().getName() : "");

            String section = "";
            if (StringUtils.isNotEmpty(client.getProvince())){
                section += client.getProvince() + "-";
            }
            if (StringUtils.isNotEmpty(client.getCity())){
                section += client.getCity() + "-";
            }
            if (StringUtils.isNotEmpty(client.getCounty())){
                section += client.getCounty() + "-";
            }
            if (StringUtils.isNotEmpty(section)){
                section = section.substring(0, section.length()-1);
            }
            rMap.put("area", section);
            rMap.put("createDate", DataUtil.DateToString(client.getCreateDate(), "yyyy-MM-dd"));
            dataRows.add(JSONObject.fromObject(rMap));
        }
        long total =pager.getTotalCount();
        if(total%rows==0){
            total = total/rows;
        }else{
            if(total<rows){
                total = 1;
            }else{
                total = total/rows + 1;
            }
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        data.put("total",total);
        data.put("records",pager.getTotalCount());
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String clientGrid(){
        pager = new Pager();
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        pager = clientService.findByPagerAndStates(pager, new StateEnum[]{StateEnum.Enable});
        List<Client> usersList;
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("name", name);
        params.put("state", new StateEnum[]{StateEnum.Enable});
        if(filters==null && _search.equals(true)){
            usersList=(List<Client>) pager.getList();
        }
        else{
            params=getSearchFilterParams(_search,params,filters);
            pager= clientService.findByPager(pager, params, sidx, BaseEnum.OrderType.valueOf(sord));
            usersList= (List<Client>) pager.getList();
        }
        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Client client : usersList){
            rMap = new HashMap<String, Object>();
            rMap.put("name",client.getName());
            rMap.put("subname",client.getSubName());
            rMap.put("id",client.getId());
            dataRows.add(JSONObject.fromObject(rMap));
        }
        data.put("dataRows", JSONArray.fromObject(dataRows));
        data.put("records", pager.getTotalCount());
        data.put("page",page);
        data.put("rows",rows);
        int total;
        if(pager.getTotalCount()%pager.getPageSize() !=0){
            total = pager.getTotalCount()/pager.getPageSize() + 1;
        }
        else{
            total=pager.getTotalCount();
        }
        data.put("total",total);
        return ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){
        section = "";

        if(StringUtils.isNotEmpty(keyId)){
            client = clientService.get(keyId);
        }

        if (StringUtils.isNotEmpty(linkmanId)){
            Linkman linkman = linkmanService.get(linkmanId);
            client = linkman.getClient();
        }

        if (StringUtils.isNotEmpty(client.getProvince())){
            section += client.getProvince() + "-";
        }
        if (StringUtils.isNotEmpty(client.getCity())){
            section += client.getCity() + "-";
        }
        if (StringUtils.isNotEmpty(client.getCounty())){
            section += client.getCounty() + "-";
        }
        if (StringUtils.isNotEmpty(section)){
            section = section.substring(0, section.length()-1);
        }

        return "read";
    }

    public String input(){
        if (StringUtils.isNotEmpty(keyId)){
            client = clientService.get(keyId);
        }
        Company company = usersService.getCompanyByUser();
        Map<String,Object> rMap=null;
        typesArrayList = new ArrayList<Map<String, Object>>();
        for(Dict typeObj:dictService.listFormDefinedEnable(DictBean.DictEnum.ClientType, company.getId())){
            rMap=new HashMap<String, Object>();
            rMap.put("id",typeObj.getId());
            rMap.put("name",typeObj.getName());
            rMap.put("selected","");
            if(client!=null && client.getType()!=null) {
                if(client.getType().getId().equals(typeObj.getId())){
                    rMap.put("selected","selected");
                }
            }
            typesArrayList.add(rMap);
        }
        return  "input";
    }

    public void isUniqueByName() {
        PrintWriter out= null;
        try {
            out=getResponse().getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String preId = usersService.getCompanyByUser().getId();
        boolean isUsed = false;
        Map<String,Object> mp = new HashMap<String, Object>();
        mp.put("name",newValue);
        List<Client> clts = (List<Client>)clientService.findByPager(null, mp).getList();

        if (clts.size() > 0) {
            for (Client cclt:clts) {
                if (((StringUtils.isNotEmpty(keyId) && !cclt.getId().equals(keyId)) || StringUtils.isEmpty(keyId))
                        && cclt.getCompany().getId().equals(preId)) {
                    isUsed = true;
                    break;
                }
            }
        }

        if (isUsed) {
            out.print("false");
        } else {
            out.print("true");
        }

    }

    public String save(){
        if(StringUtils.isNotEmpty(keyId)){
            client = clientService.get(keyId);
        }else{
            client = new Client();
            client.setCreater(usersService.getLoginInfo());

        }
        if (StringUtils.isNotEmpty(dictId)){
            type = dictService.get(dictId);
            client.setType(type);
        }

        client.setName(name);
        client.setCity(city);
        client.setClientPhotoIds(clientPhotoIds);
        client.setCounty(county);
        client.setInvoiceTitle(invoiceTitle);
        //client.setLinkman(linkman);
        client.setCompany(usersService.getCompanyByUser());

        client.setProvince(province);
        client.setRemark(remark);
        client.setSitutation(situtation);
        client.setSubName(subName);
        client.setState(StateEnum.Enable);
        if(StringUtils.isNotEmpty(keyId)){
            clientService.update(client);
        }else{
            String no = authCodeService.createAuthCode("client");
            client.setNo(no);
            clientService.save(client);
        }
        return ajaxHtmlCallback("200", "保存成功！","操作状态");
    }

    public String delete(){
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("400", "请选择客户信息！","操作状态");
        }
        Client client = clientService.get(keyId);

        Map<String,Object> params = new HashMap<String,Object>();
        params.put("client", client);
        List<ProInfo> proInfoList = proInfoService.getList(params);
        if (proInfoList.size() > 0){
            return ajaxHtmlCallback("400", "当前客户存在项目！","操作状态");
        }

        List<Linkman> linkmans = linkmanService.getList(params);
        if (linkmans.size() > 0){
            return ajaxHtmlCallback("400", "请先删除联系人！","操作状态");
        }
        client.setState(StateEnum.Delete);
        clientService.update(client);
        return ajaxHtmlCallback("200", "删除成功！","操作状态");
    }

    @Override
    public Pager getPager() {
        return pager;
    }

    @Override
    public void setPager(Pager pager) {
        this.pager = pager;
    }

    public Client getClient() {
        return client;
    }

    public void setClient(Client client) {
        this.client = client;
    }

    public List<Client> getClientList() {
        return clientList;
    }

    public void setClientList(List<Client> clientList) {
        this.clientList = clientList;
    }

    @Override
    public String getKeyId() {
        return keyId;
    }

    @Override
    public void setKeyId(String keyId) {
        this.keyId = keyId;
    }

    public String getSubName() {
        return subName;
    }

    public void setSubName(String subName) {
        this.subName = subName;
    }

    public String getInvoiceTitle() {
        return invoiceTitle;
    }

    public void setInvoiceTitle(String invoiceTitle) {
        this.invoiceTitle = invoiceTitle;
    }

    public Dict getType() {
        return type;
    }

    public void setType(Dict type) {
        this.type = type;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCounty() {
        return county;
    }

    public void setCounty(String county) {
        this.county = county;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public String getSitutation() {
        return situtation;
    }

    public void setSitutation(String situtation) {
        this.situtation = situtation;
    }

    public Set<Linkman> getLinkman() {
        return linkman;
    }

    public void setLinkman(Set<Linkman> linkman) {
        this.linkman = linkman;
    }

    public String getClientPhotoIds() {
        return clientPhotoIds;
    }

    public void setClientPhotoIds(String clientPhotoIds) {
        this.clientPhotoIds = clientPhotoIds;
    }

    public ArrayList<Map<String, Object>> getTypesArrayList() {
        return typesArrayList;
    }

    public void setTypesArrayList(ArrayList<Map<String, Object>> typesArrayList) {
        this.typesArrayList = typesArrayList;
    }

    public String getDictId() {
        return dictId;
    }

    public void setDictId(String dictId) {
        this.dictId = dictId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSection() {
        return section;
    }

    public void setSection(String section) {
        this.section = section;
    }

    public String getLinkmanId() {
        return linkmanId;
    }

    public void setLinkmanId(String linkmanId) {
        this.linkmanId = linkmanId;
    }
}
